package com.learn.spring_mvc.controller;

import org.apache.commons.io.IOUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

@Controller
public class UploadController {
    /**
     * 文件上传（参数类型变为数据即可上传多个文件）
     */
    @PostMapping("/upload")
    public String upload(@RequestBody MultipartFile file) throws IOException {
        // 将上传为文件保存
        // 1️⃣获取文件上传输入流
        InputStream inputStream = file.getInputStream();
        
        // 2️⃣获取文件拷贝输出流
        OutputStream outputStream = new FileOutputStream("/Users/chenjie/ideas/spring/spring-framework/src/main/resources/uploads/" + file.getOriginalFilename());
        
        // 3️⃣执行文件拷贝
        IOUtils.copy(inputStream, outputStream);
        
        // 4️⃣关闭资源
        inputStream.close();
        outputStream.close();
        
        return "/index.jsp";
    }
}
